<template>
    <div class="container">
        <CommentList :comments="comments" 
                     type="user"
                     v-if="userinfo.openId"
        ></CommentList>
        <div v-if="userinfo.openId">
          <div class="page-title">我的图书</div>
          <Card v-for="book in books" 
                :key="book.id"
                :book='book'
          ></Card>
          <div v-if="!books.length">暂时还没有添加图书，快去添加几本吧</div>
        </div>
    </div>
</template>

<script type="text/ecmascript-6">
import { get } from "@/util";
import CommentList from "@/components/CommentList";
import Card from "@/components/Card";

export default {
  data() {
    return {
      comments: [],
      openid: '',
      userinfo: {},
      books: []
    };
  },
  components: {
    CommentList,
    Card
  },
  
  // 每次切到此页面调用
  onShow(){
    if(!this.userinfo.openId) {
      let userinfo = wx.getStorageSync('userinfo')
      if(userinfo) {
        this.userinfo = userinfo
        this.init()
      }
    }
  },

  methods: {
    // 初始化评论
    init() {
      wx.showNavigationBarLoading()
      // 获取评论
      this.getComments()
      // 获取图书
      this.getBooks()
      wx.hideNavigationBarLoading()
    },

    // 获取评论
    async getComments(){
      const comments = await get('/weapp/commentlist',{
        openid: this.userinfo.openId
      })
      this.comments = comments.list
    },

    // 获取图书
    async getBooks() {
      const books = await get('/weapp/booklist',{
        openid: this.userinfo.openId
      })
      this.books = books.list
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.init()
    wx.stopPullDownRefresh()
  }
};
</script>

<style scoped>
</style>
